<template>
    <div class="btnContainerBox">
        <template v-for="(btn, index) of getButtons">
            <!-- 当按钮的数量小于最大数时，或者显示最后一个按钮 -->
            <template v-if="index < buttonCount - 1 || index === buttons.length - 1">
                <div
                    :class="{ 'bpm-task-button': true, 'bpm-task-button-primary': JSON.parse(btn.style) }"
                    :key="btn.id"
                    @click="handMethod(btn)"
                >
                    <loading-outlined v-if="getLoading(btn)"/>
                    <rx-icon-show size="14px" v-if="btn.icon" :icon="getBtnIcon(btn.icon)"></rx-icon-show>
                    <span class="process-btn-name">{{ getI18Name(btn, 'name') }}</span>
                </div>
            </template>
            <a-dropdown v-else-if="index == buttonCount - 1">
                <a class="ant-dropdown-link" @click="(e) => e.preventDefault()"> 更多
                    <down-outlined/>
                </a>
                <template #overlay>
                    <a-menu>
                        <template v-for="(innerBtn, index) of getButtons">
                            <a-menu-item v-if="index >= buttonCount - 1 && index < getButtons.length - 1">
                                <div :key="innerBtn.id" @click="handMethod(innerBtn)">
                                    <rx-icon-show size="14px" v-if="innerBtn.icon" :icon="getBtnIcon(innerBtn.icon)"></rx-icon-show>
                                    <span class="process-btn-name">{{ getI18Name(innerBtn, 'name') }}</span>
                                </div>
                            </a-menu-item>
                        </template>
                    </a-menu>
                </template>
            </a-dropdown>
        </template>
        <rx-spin v-if="spinShow" :text="i18n('instStart.desc', '正在提交...,请稍等。')"></rx-spin>
    </div>
</template>

<script>
// import {Util, RxSpin, RxTextList,RxIconShow} from '@lowcode/jpaas-base-lib';
import {Util, RxSpin,RxIconShow} from '@lowcode/jpaas-base-lib';
import {App} from '@lowcode/jpaas-share-component';
import BpmInstApi from '@/common/api/bpm/bpmInst';
import BpmInstStartConfirm from '../components/BpmInstStartConfirm.vue'
import BpmInstStart from './BpmInstStart.vue'
import FlowUtil from '@/views/modules/bpm/js/FlowUtil';
import startButton from './js/startButton'
import formBase from './js/formBase.js';
import {Modal} from 'ant-design-vue';

export default {
    name: 'ProcessToolBar',
    mixins: [formBase, FlowUtil, startButton, App],
    components: {
        RxSpin,
        RxIconShow
    },
    props: {
        processConfig: {type: Object},
        defId: {type: String},
        instId: {type: String},
        mainDefId: {type: String},
        bpmActionType: { type: String },
        mainTaskId: {type: String},
        vars: {
            type: Object, default: () => {
            }
        },
    },
    computed: {
        //显示按钮数量
        buttonCount() {
            return this.processConfig.startMaxButton || 4
        }
    },
    data() {
        return {
            saveDraftStatus: false,
            startProcessStatus: false,
            buttons: [],
            startConfirm: false,
            spinShow: false,
            submited: false,
            saveed: false,
            //是否需要弹出确认的对话框
            needConfirmDlg: false,
            broadCastChannel:new BroadcastChannel('broadCastChannel'),
        }
    },

    methods: {
        getBtnIcon(icon){
            try {
                let iconConfig = new Function(`return ${icon}`)();
                return iconConfig.icon
            }catch (e){
                return icon
            }
        },
        getI18Name(item) {
            if (item.i18nJson) {
                return this.$i18(item.i18nJson, item.name) || item.name;
            }
            return item.name;
        },
        getLoading(btn) {
            if (!btn.hasOwnProperty('loading')) {
                return false
            }
            return this[btn.loading]
        },
        i18n(name, text, key) {
            return this.$ti18(name, text, 'bpmInst', key)
        },
        startSubProcess(alias) {
            var self_ = this
            var formType = this.processConfig.formType
            var formData = this.getFormData();
            BpmInstApi.getSubProcessFormData({
                defKey: alias,
                mainDefId: this.defId,
                instId: this.instId,
                formData: formData,
            }).then((res) => {
                if (!res.success) {
                    return
                }
                self_.startFlowPage(res.data)
            })
        },
        startFlowPage(data) {
            Util.open(
                {
                    component: BpmInstStart,
                    curVm: this,
                    max: true,
                    title: data.defName + this.i18n('instStart.title', '流程启动'),
                    data: {
                        defId: data.defId,
                        mainDefId: this.defId,
                        formData: data.formData,
                        vars: data.vars,
                    },
                },
                function (action) {
                }
            )
        },
        async startProcess() {
            if (this.submited) {
                this.$message.error(this.i18n('instStart.repeatTips', '请勿重复提交流程！'))
                return
            }
            var validResult = await this.valid(true, "start")
            if (!validResult.success) {
               // this.$message.warn(validResult.msg)
                return
            }

            let self_ = this
            if (self_.startConfirm && !self_.needConfirmDlg) {
                //启动流程确认
                Modal.confirm({
                    title: this.$ti18('rxMsa.tipsInfo', '提示信息'),
                    content: self_.i18n('instStart.confirmTips', '确认提交审批吗？'),
                    cancelText: this.$ti18('rxForm.cancelBtn', '取消'),
                    okText: this.$ti18('rxForm.ackBtn', '确认'),
                    zIndex: 20000,
                    async onOk() {
                        self_.startFlow()
                    },
                    onCancel() {
                    },
                })
            } else if (self_.needConfirmDlg) {
                //是否确认
                let conf = {
                    curVm: self_,
                    title: self_.i18n('instStart.confirmTitle', '流程启动确认'),
                    component: BpmInstStartConfirm,
                    data: {
                        processConfig: self_.processConfig,
                        defId: self_.defId,
                        instId: self_.instId,
                        formData: self_.getFormData(),
                        //幂等号
                        idempotenceid:this.parentVm.idempotenceid
                    },
                    widthHeight: ['800px', '520px'],
                }
                Util.open(conf, function (action, res) {
                    if (action != 'ok') return
                    //启动流程成功
                    self_.closeWindow(res.data);
                })
            } else {
                self_.startFlow()
            }
        },
        async valid(validRquired,action) {
            var res = { success: true }
            //表单保存校验
            if (this.processConfig.formType === 'custom') {
                res = await this.customForm.valid(validRquired,action)
                return res
            } else if (this.processConfig.formType === 'outsideUrl') {
                res = await this.outSideUrlForm.valid(validRquired,action)
                return res
            } else {
                res = await this.rxForms.valid(validRquired, action);
                return res
            }
        },
        async afterSubmit(result, formJson) {
            if (this.processConfig.formType != 'custom' && this.processConfig.formType != 'outsideUrl') {
                let formBuild = this.getFormVm();
                if (formBuild._afterSubmit) {
                    //如果_afterSubmit有返回结果并且rtn为success则返回。
                    let rtn = await formBuild._afterSubmit(result, formJson);
                    if (rtn && !rtn.success) {
                        this.$message.warn(rtn.msg);
                    }
                }
            }
        },
        async startFlow() {

            let validResult = await this.valid(true,"start")
            if (!validResult.success) {
                this.$message.warn(validResult.msg)
                return;
            }
            let self = this;
            self.spinShow = true;
            this.startProcessStatus = true;

            let data = this.getData()

            var varData = {mainDefId: this.mainDefId, mainTaskId: this.mainTaskId}
            if (this.vars) {
                varData = Object.assign(varData, this.vars)
            }
            data.vars = JSON.stringify(varData)
            BpmInstApi.startProcess(data)
                .then((res) => {
                    self.afterSubmit(res, data)
                    self.startProcessStatus = false
                    self.spinShow = false
                    if (res.success) {
                        this.broadCastChannel.postMessage({
                            type: "refreshTask",
                        });
                        //启动流程成功
                        this.closeWindow(res.data);
                    }
                })
                .catch((error) => {
                    self.startProcessStatus = false
                    self.spinShow = false
                })
        },
        async saveDraft() {
            if ((this.parentVm.fromRoute || !this.parentVm.instId) && this.saveed) {
                this.$message.error(this.i18n('msa.saveTips', '请勿重复保存！'))
                return
            }
            this.saveDraftStatus = true
            var validResult = await this.valid(false, "draft")
            if (!validResult.success) {
                this.$message.warn(validResult.msg)
                this.saveDraftStatus = false
                return
            }
            var data = this.getData()
            var varData = {mainDefId: this.mainDefId, mainTaskId: this.mainTaskId}
            if (this.vars) {
                varData = Object.assign(varData, this.vars)
            }
            data.vars = JSON.stringify(varData)
            BpmInstApi.saveDraft(data).then((res) => {
                if (res.success) {
                    this.$notification.success({
                        message: this.$ti18('rxMsa.actionTips', '操作提示'),
                        description: res.message,
                    })
                    //重新加载表单数据。
                    this.closeWindow(res.data);
                } else {
                    this.$notification.warning({
                        message: this.$ti18('rxMsa.actionTips', '操作提示'),
                        description: res.message,
                    })
                }

                this.saveDraftStatus = false
                this.saveed = true
                this.afterSubmit(res, data)
            })
        },
        formPrint() {
            var url = import.meta.env.JPAAS_BASE_URL;
            if(url.includes('main')){
                url += '/flowPrint/' + this.defId
            }else {
                url += '/' + this.parentVm.appKey + '/flowPrint/' + this.defId
            }
            if (this.instId) {
                url += '/' + this.instId
            } else {
                url += '/-1'
            }
            let appId = this.curApp.appId;
            url += `?appId=${appId}`;
            //获取表单数据
            window.formData = this.getData()

            window.open(url)
        },
        closeWindow(data) {
            this.submited = true;
            if (this.parentVm.layerid) {
                Util.closeWindow(this.parentVm, 'ok', data)
            } else if (this.parentVm.fromRoute) {
                this.parentVm.$bus.emit('closeTab', { action: 'current' })
            }else {
                let eventObj = {action: 'start', data: data}
                this.parentVm.$bus.emit('flowEvent', eventObj)
            }
        },
        updateBtnAuth(){
            let btns = this.changeBtnHandle(this.bpmActionType,this.processConfig,this.processConfig.buttonConfigs);
            this.buttons = btns;
        },
    },
    watch: {
        processConfig: {
            handler(newVal, oldVal) {
                if (!newVal) {
                    return
                }
                let btns = this.changeBtnHandle(this.bpmActionType,newVal,newVal.buttonConfigs);
                this.buttons = btns;

                let fillOpinion = false
                let assignFlowUsers = false
                let startCalFlowusers = false
                let relInsts = false
                //允许选择路径
                let allowSelectPath = newVal.allowSelectPath
                let assignBatchFlowUsers = newVal.assignBatchFlowUsers
                var startOptions = newVal.startNodeOptions

                if (startOptions instanceof Array) {
                    this.startConfirm = startOptions.indexOf('startConfirm') != -1
                    fillOpinion = startOptions.indexOf('fillOpinion') != -1
                    assignFlowUsers = startOptions.indexOf('assignFlowUsers') != -1
                    startCalFlowusers = startOptions.indexOf('startCalFlowusers') != -1
                    relInsts = startOptions.indexOf('relInsts') != -1
                }
                if (
                    assignBatchFlowUsers ||
                    fillOpinion ||
                    assignFlowUsers ||
                    startCalFlowusers ||
                    allowSelectPath ||
                    relInsts
                ) {
                    //需要显示弹出对话框
                    this.needConfirmDlg = true
                }
            },
        },
    },
}
</script>

<style scoped>
.process-btn-name{
    margin-left: 4px;
}
.btnContainerBox {
    display: flex;
    align-items: center;
}

.bpm-task-button {
    height: 30px;
    line-height: 30px;
    padding: 0 12px;
    cursor: pointer;
}

.bpm-task-button:hover {
    color: #4285f4;
}

.bpm-task-button.bpm-task-button-primary {
    background-color: #4285f4;
    color: #fff;
    border-radius: 4px;
}

.ant-dropdown-link {
    padding: 0 12px;
}

.spinContainer {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: 999;
    padding-top: 40px;
    text-align: center;
}

.spinCenter {
    text-align: left;
    display: inline-block;
    padding: 10px;
    border-radius: 3px;
    background: #fff;
    position: absolute;
    box-shadow: 0px 0px 5px #ddd;
    top: 40%;
}
</style>
